<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace plugins\wechat_zhl;//Demo插件英文名，改成你的插件英文就行了
use cmf\lib\Plugin;
use think\Db;
use plugins\wechat_zhl\model\WechatModel;
/**
 * WechatZhlPlugin
 */
class WechatZhlPlugin extends Plugin
{

    public $info = [
        'name'        => 'WechatZhl',
        'title'       => '微信公众平台',
        'description' => '微信公众平台',
        'status'      => 1,
        'author'      => 'zhl',
        'version'     => '1.0'
    ];

    public $hasAdmin = 1;//插件是否有后台管理界面

    // 插件安装
    public function install()
    {
        return true;//安装成功返回true，失败false
    }

    // 插件卸载
    public function uninstall()
    {
        return true;//卸载成功返回true，失败false
    }

    //实现的微信自动登陆钩子方法
    public function weixinlogin($param)
    {
        if(isset($param['store_id'])){
            session('yylm_store_id',$param['store_id']);
        }
        if($this->is_weixin()){
            $userId = cmf_get_current_user_id();
            $flag=0;
            if(!$userId){
                //未登录
                $flag=1;
            }else{
                $rs_u_info=Db::name('user')->where('id',$userId)->find();
               if($rs_u_info==null){
                    session("user", null);
                   $flag=2;
                }else{
                 if($rs_u_info['openid']==null){
                      //未绑定
                      $flag=2;
                  }
               }
                
            }
            if($flag>0){
                $WechatSettings = cmf_get_option('wechat_settings');
                if(!empty($WechatSettings['default'])){
                    $defaultWechat =  $WechatSettings['default'];
                    $redirecturl=$this->get_url();
                    if(!empty($param['code'])){
                        $rs=$this->get_weixin_info($defaultWechat['app_id'],$defaultWechat['app_secret'],$param['code']);
                        
                        $user_info=$this->get_weixin_user_info($rs['access_token'],$rs['openid']);
                        if($flag==1){
                            //未登录
                            //查找openid
                            $rs_u_info=Db::name('user')->where('openid',$user_info['openid'])->find();
                            if($rs_u_info==null){
                                $user['user_pass'] = md5(time());
                                $user['avatar'] = $user_info['headimgurl'];
                                $user['last_login_ip'] = get_client_ip(0, true);
                                $user['last_login_time'] = time();
                                $user['create_time'] = time();
                                $user['openid'] = $user_info['openid'];
                                $user['user_nickname'] = $user_info['nickname'];
                                $user['sex'] = $user_info['sex'];
                                if(isset($param['uid'])){
                                    $user['tj_user'] = $param['uid'];
                                }
                                $uid= Db::name('user')->insertGetId($user);
                                $rs_u_info=Db::name('user')->where('id',$uid)->find();
                                if(isset($param['uid'])){
                                  	user_free_card($param['uid'],$uid);
								}
                            }
                        }
                        if($flag==2){
                            //未绑定
                            $user['openid'] = $user_info['openid'];
                            Db::name('user')->where('id',$userId)->update($user);
                            if(isset($param['uid'])){
                               user_free_card($param['uid'],$userId);
							}
                        }
                        cmf_update_current_user($rs_u_info);
                  
                        $token = cmf_generate_user_token($rs_u_info['id'], 'weixin');
                        if (!empty($token)) {
                            session('token', $token);
                        }
                    }else{
                        $this->get_access_token($defaultWechat['app_id'],$redirecturl);
                    }
                }
            }
        }
    }

   public function weixinshare($param){
   	$WechatSettings = cmf_get_option('wechat_settings');
     if(!empty($WechatSettings['default'])){
     	$_WechatModel = new WechatModel();
        $url          = request()->url(true);//获取url
        $jsSign       = $_WechatModel->getJsSign($url);//获取jsapi签名
        $shareConfig  = [
                'debug'     => false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                'jsApiList' => [
                    'onMenuShareTimeline',
                    'onMenuShareAppMessage',
                    'onMenuShareQQ',
                    'onMenuShareWeibo',
                    'onMenuShareQZone'
                ] // 必填，需要使用的JS接口列表
        ];
        $shareConfig = array_merge($shareConfig, (array)$jsSign);
        $share = [
            'link'=>$url,
        ];
        $share = array_merge($param,$share);
        $this->assign([
            'share'       => $share,
            'shareConfig' => $shareConfig
        ]);
        echo $this->fetch('widget2');
     }
   
   }
    private function is_weixin(){
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            return true;
        }else{
            return false;
        }
    }
    private function get_url(){
        $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
        $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
        $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
        $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.$_SERVER['QUERY_STRING'] : $path_info);
        return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;

    }

    function get_access_token($appid,$redirecturl,$scope='snsapi_userinfo'){
        $redirecturl=urlencode($redirecturl);
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirecturl.'&response_type=code&scope='.$scope.'&state=state#wechat_redirect';
        // $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirecturl.'&response_type=code&scope='.$scope.'&state=123#wechat_redirect';
        header("location:".$url);
        exit;
    }
    function get_weixin_info($appid,$appsecret,$code){
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
        $rs = file_get_contents($url);
        $rs = json_decode($rs,TRUE);
        return $rs;
    }

    function get_weixin_user_info($token,$openid){
        $abs_url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$token."&openid=".$openid."&lang=zh_CN";
        $abs_url_data = file_get_contents($abs_url);
        $obj_data=json_decode($abs_url_data,true);
        return $obj_data;
    }



}